/*
 * @lc app=leetcode.cn id=993 lang=javascript
 *
 * [993] 二叉树的堂兄弟节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
var getDepth = function (root, x, depth) {
  if (root === null) {
    return 0;
  }
  if (root.val === x) {
    return depth;
  } else {
    return getDepth(root.left, x, depth + 1) || getDepth(root.right, x, depth + 1)
  }
}

var isBrother = function (root, x, y) {
  if (root === null) return false;
  if (root.left === null && root.right === null) return false;
  if (root.left === null) {
    return isBrother(root.right, x, y);
  }
  if (root.right === null) {
    return isBrother(root.left, x, y);
  }
  if (root.left.val === x && root.right.val === y || root.left.val === y && root.right.val === x) {
    return true;
  }
  return isBrother(root.left, x, y) || isBrother(root.right, x, y);
}
/**
 * @param {TreeNode} root
 * @param {number} x
 * @param {number} y
 * @return {boolean}
 */
var isCousins = function (root, x, y) {
  if (getDepth(root, x, 1) === getDepth(root, y, 1)) {
    return !isBrother(root, x, y);
  } else {
    return false;
  }
};
// @lc code=end

